package me.project.jobster.controller;

import com.alibaba.fastjson.JSON;
import me.project.jobster.common.constant.GlobalConstants;
import me.project.jobster.common.util.Response;
import me.project.jobster.dao.mybatis.model.Notification;
import me.project.jobster.service.FollowService;
import me.project.jobster.service.FriendService;
import me.project.jobster.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

/**
 * @author Mcdull
 * @date 2018-4-27
 */
@Controller
@RequestMapping("message")
public class MessageController extends BaseController {

    @Autowired
    private MessageService messageService;
    @Autowired
    private FriendService friendService;
    @Autowired
    private FollowService followService;

    /**
     * message page
     * @param request
     * @param model
     * @return
     */
    @GetMapping("index")
    public String index(HttpServletRequest request, Model model){
        HttpSession session = request.getSession();
        session.setAttribute(GlobalConstants.MENU, "5");
        String userId = String.valueOf(session.getAttribute("user_id"));
        List<Notification> list = messageService.getAllMessage(userId, GlobalConstants.MSG_UNREAD);
        model.addAttribute("messageList1", list);
        List<Notification> list2 = messageService.getAllMessage(userId, GlobalConstants.MSG_READ);
        model.addAttribute("messageList2", list2);

        countMsgUnread(request);
        return "message/message";
    }

    /**
     * friend apply
     * type = 0
     * @param request
     * @return
     */
    @GetMapping("/apply/friend")
    @ResponseBody
    public String applyForFriend(HttpServletRequest request){
        Response response = Response.getInstance("","");
        HttpSession session = request.getSession();
        String friendId = request.getParameter("sId");
        String userId = String.valueOf(session.getAttribute("user_id"));
        boolean isFriend = friendService.isFriend(userId,friendId);
        if (isFriend){
            // friend is already a friend
            response.setSuccess(false);
            response.setRespMessage("You are already friends!");
            return JSON.toJSONString(response);
        } else {
            Notification notification = new Notification();
            notification.setSender(userId);
            notification.setSendName((String) session.getAttribute("user_name"));
            notification.setReceiver(friendId);
            notification.setType(GlobalConstants.MSG_FRIEND_APPLY);
            notification.setStatus(GlobalConstants.MSG_UNREAD);
            notification.setMassage("You get a friend application!");
            messageService.sendMessage(notification);

            response.setSuccess(true);
            response.setRespMessage("The application message has been sent successfully!");
            return JSON.toJSONString(response);
        }
    }

    /**
     * job apply
     * type = 1
     * @param request
     * @return
     */
    @GetMapping("/apply/job")
    @ResponseBody
    public String applyForJob(HttpServletRequest request){
        Response response = Response.getInstance("","");
        HttpSession session = request.getSession();
        String pId = request.getParameter("pId");
        String cId = request.getParameter("cId");
        String userId = String.valueOf(session.getAttribute("user_id"));

        Notification notification = new Notification();
        notification.setSender(userId);
        notification.setSendName((String) session.getAttribute("user_name"));
        notification.setReceiver(cId);
        notification.setType(GlobalConstants.MSG_POSITION_APPLY);
        notification.setStatus(GlobalConstants.MSG_UNREAD);
        notification.setMassage("You get a job application!");
        notification.setExt1(pId);
        messageService.sendMessage(notification);

        response.setSuccess(true);
        response.setRespMessage("The application message has been sent successfully!");
        return JSON.toJSONString(response);
    }

    /**
     * follow a company
     * type = 4
     * @param request
     * @return
     */
    @GetMapping("/apply/company")
    @ResponseBody
    public String follow(HttpServletRequest request){
        Response response = Response.getInstance("","");
        HttpSession session = request.getSession();
        String cId = request.getParameter("cId");
        String userId = String.valueOf(session.getAttribute("user_id"));

        if(followService.followCompany(userId,cId)){
            Notification notification = new Notification();
            notification.setSender(userId);
            notification.setSendName((String) session.getAttribute("user_name"));
            notification.setReceiver(cId);
            notification.setType(GlobalConstants.MSG_COMPANY_FOLLOW);
            notification.setStatus(GlobalConstants.MSG_UNREAD);
            notification.setMassage("You get a follower!");
            messageService.sendMessage(notification);
        }

        response.setSuccess(true);
        response.setRespMessage("You have succeeded in following to the company!");
        return JSON.toJSONString(response);
    }

    /**
     * forward a job info
     * type = 2
     * @param request
     * @return
     */
    @GetMapping("/forward/job")
    @ResponseBody
    public String forwardJobInfo(HttpServletRequest request){
        Response response = Response.getInstance("","");
        HttpSession session = request.getSession();
        String[] friendIdList = request.getParameter("friendIdList").split(",");
        String positionId = request.getParameter("pId");
        String userId = String.valueOf(session.getAttribute("user_id"));
        String userName = String.valueOf(session.getAttribute("user_name"));
        for (String s : friendIdList) {
            Notification notification = new Notification();
            notification.setType(GlobalConstants.MSG_POSITION_FORWARD);
            notification.setStatus(GlobalConstants.MSG_UNREAD);
            notification.setReceiver(s);
            notification.setSender(userId);
            notification.setSendName(userName);
            notification.setExt1(positionId);
            notification.setMassage(userName + " has send a message to you just now!");
            messageService.sendMessage(notification);
        }

        response.setSuccess(true);
        response.setRespMessage("You have succeeded in following to the company!");
        return JSON.toJSONString(response);
    }


    /**
     * mark the message status as read
     * @param request
     * @return
     */
    @GetMapping("/read")
    public String markAsRead(HttpServletRequest request, Model model){
        HttpSession session = request.getSession();
        session.setAttribute(GlobalConstants.MENU, "5");

        //read
        int id = Integer.valueOf(request.getParameter("id"));
        messageService.markAsRead(id);

        //back to the page
        String userId = String.valueOf(session.getAttribute("user_id"));
        List<Notification> list = messageService.getAllMessage(userId, GlobalConstants.MSG_UNREAD);
        model.addAttribute("messageList1", list);
        List<Notification> list2 = messageService.getAllMessage(userId, GlobalConstants.MSG_READ);
        model.addAttribute("messageList2", list2);

        countMsgUnread(request);
        return "message/message";
    }

    /**
     * accept the application
     * @param friendId
     * @param friendName
     * @param request
     * @return
     */
    @RequestMapping("/friend/accept")
    @ResponseBody
    public String acceptFriend(@RequestParam("friendId") String friendId,
                               @RequestParam("friendName") String friendName,
                               HttpServletRequest request){
        Response response = Response.getInstance("","");
        HttpSession session = request.getSession();
        String userId = String.valueOf(session.getAttribute("user_id"));
        String userName = String.valueOf(session.getAttribute("user_name"));

        boolean isFriend = friendService.isFriend(userId,friendId);
        if (isFriend){
            response.setRespMessage("Your are already friends!");
            return JSON.toJSONString(response);
        }
        friendService.beFriends(userId,userName,friendId,friendName);

        //send a msg
        Notification notification = new Notification();
        notification.setType(GlobalConstants.MSG_REPLY);
        notification.setStatus(GlobalConstants.MSG_UNREAD);
        notification.setReceiver(friendId);
        notification.setSender(userId);
        notification.setSendName(userName);
        notification.setMassage(userName + " has just agreed to your friend application!");
        messageService.sendMessage(notification);

        response.setSuccess(true);
        response.setRespMessage("You have accept the application successfully!");
        return JSON.toJSONString(response);
    }

    /**
     * refuse the application
     * type = 5
     * @param friendId
     * @param friendName
     * @param request
     * @return
     */
    @RequestMapping("/friend/refuse")
    @ResponseBody
    public String refuseFriend(@RequestParam("friendId") String friendId,
                               @RequestParam("friendName") String friendName,
                               HttpServletRequest request) {
        Response response = Response.getInstance("", "");
        HttpSession session = request.getSession();
        String userId = String.valueOf(session.getAttribute("user_id"));
        String userName = String.valueOf(session.getAttribute("user_name"));

        boolean isFriend = friendService.isFriend(userId, friendId);
        if (isFriend) {
            response.setRespMessage("Your are already friends!");
            return JSON.toJSONString(response);
        }
        //send a msg
        Notification notification = new Notification();
        notification.setType(GlobalConstants.MSG_REPLY);
        notification.setStatus(GlobalConstants.MSG_UNREAD);
        notification.setReceiver(friendId);
        notification.setSender(userId);
        notification.setSendName(userName);
        notification.setMassage(userName + " has just refused your friend application!");
        messageService.sendMessage(notification);

        response.setSuccess(true);
        response.setRespMessage("You have refused the application successfully!");
        return JSON.toJSONString(response);

    }


    /**
     * send message to another student
     * @param request
     * @return
     */
    @RequestMapping("/sendMsg")
    @ResponseBody
    public String sendMsg(@RequestBody Map<String, String> requestBodyParams,
                          HttpServletRequest request) {
        Response response = Response.getInstance("", "");
        HttpSession session = request.getSession();
        String userId = String.valueOf(session.getAttribute("user_id"));
        String userName = String.valueOf(session.getAttribute("user_name"));
        String sId = requestBodyParams.get("sId");
        String sName = requestBodyParams.get("sName");
        String msg = requestBodyParams.get("msg");

        //send a msg
        Notification notification = new Notification();
        notification.setType(GlobalConstants.MSG_REPLY);
        notification.setStatus(GlobalConstants.MSG_UNREAD);
        notification.setReceiver(sId);
        notification.setSender(userId);
        notification.setSendName(userName);
        notification.setMassage(msg);
        messageService.sendMessage(notification);

        response.setSuccess(true);
        response.setRespMessage(sName + " has receive your message!");
        return JSON.toJSONString(response);

    }
}
